import { defineView } from "@/routers/tools.mjs";

class InvoiceController {
  qty = 1;

  cost = 2;

  /**
   * @type {'USD' | 'EUR' | 'CNY'}
   */
  inCurr = "EUR";

  currencies = ["USD", "EUR", "CNY"];

  usdToForeignRates = {
    USD: 1,
    EUR: 0.74,
    CNY: 6.09,
  };

  /**
   * @param {'USD' | 'EUR' | 'CNY'} outCurr
   * @returns {number}
   */
  total(outCurr) {
    return this.convertCurrency(this.qty * this.cost, this.inCurr, outCurr);
  }

  /**
   * @param {number} amount
   * @param {'USD' | 'EUR' | 'CNY'} inCurr
   * @param {'USD' | 'EUR' | 'CNY'} outCurr
   * @returns {number}
   */
  convertCurrency(amount, inCurr, outCurr) {
    return (
      (amount * this.usdToForeignRates[outCurr]) /
      this.usdToForeignRates[inCurr]
    );
  }

  pay() {
    // eslint-disable-next-line no-alert
    window.alert("Thanks!");
  }
}

/**
 * @type {DefineView}
 */
const clView = defineView({
  controller: InvoiceController,
  controllerAs: "invoice",
  template: /* HTML */ html`
    <div>
      <b>Invoice:</b>
      <div>
        Quantity:
        <input
          class="form-control"
          type="number"
          min="0"
          ng-model="invoice.qty"
          required
        />
      </div>
      <div>
        Costs:
        <input
          class="form-control"
          type="number"
          min="0"
          ng-model="invoice.cost"
          required
        />
        <select ng-model="invoice.inCurr">
          <option ng-repeat="c in invoice.currencies">{{c}}</option>
        </select>
      </div>
      <div>
        <b>Total:</b>
        <p ng-repeat="c in invoice.currencies">
          {{invoice.total(c) | currency:c}}
        </p>
        <br />
        <button class="btn" ng-click="invoice.pay()">Pay</button>
      </div>
    </div>
  `,
});

export default clView;
